import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, FormArray, NgForm, NgModel, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

import * as moment from 'moment';

import { Subject } from 'rxjs';

import { BaseDirective } from '../../core/models/base-directive.model';
import { CommonService } from '../../core/services/common.service';
import { RegularExpressionConfig } from '../../core/config/regular-expression.config';
import { ValidatorFactoryService } from '../../core/services/validator-factory.service';
import { UserGeneralConfig } from '../../core/config/user-general.config';
import { UserService } from '../shared/user.service';

declare const $: any;

@Component({
    templateUrl: './add.component.html',
    styleUrls: ['../../../assets/styles/hide-element-focus-outline.css']
})
export class AddComponent extends BaseDirective implements OnInit, AfterViewInit {
    @ViewChild('login', { static: false }) private loginNameLocation;
    user: any;
    formGroup: FormGroup;
    searchName: Subject<string> = new Subject<string>();
    // msgs: Message[] = [];
    isExistedLoginName: boolean = false;
    maxDate = new Date();
    status: any[];
    nationality: any[];
    secondAddress: any[];
    firstAddress: any[];
    beijingProvince: any[] = [];
    shanghaiProvice: any[] = [];
    loginNameClass: {};

    constantOfFirstAddress = UserGeneralConfig.firstAddress;
    constantOfNation = UserGeneralConfig.nationality;
    constantOfSecondAddress = UserGeneralConfig.secondAddress;
    constantOfStatus = UserGeneralConfig.status;
    legitimateAccountOfRegExp = RegularExpressionConfig.legitimateAccount;
    legitimateIDCardOfRegExp = RegularExpressionConfig.legitimateIDCard;
    legitimateNameOfRegExp = RegularExpressionConfig.legitimateName;
    legitimatePhoneOfRegExp = RegularExpressionConfig.legitimatePhone;

    constructor(
        private elementRef: ElementRef,
        private formBuilder: FormBuilder,
        private userService: UserService,
        private validatorFactory: ValidatorFactoryService,
        private route: ActivatedRoute,
        private router: Router,
        // private confirmationService: ConfirmationService
    ) { super() }

    ngOnInit(): void {
        super.ngOnInit();

        this.createForm();
        this.prepareUserData();
        this.loadFirstAddress();
        this.loadSecondAddress();
        this.loadNationality();
        this.loadStatus();
        this.loadData();
    }

    ngAfterViewInit(): void {
        this.commonService.appendScriptChildToElement(this.elementRef, ['js/custom-form-float.js']);
    }

    back(form: NgForm): void {
        if (form.pristine) {
            this.router.navigate(['/users-demo']);
        }
    }

    cancel(): void {
    }

    confirm(): void {
        // this.router.navigate(['/users-demo']);
        // this.confirmationService.confirm({
        //     message: 'Are you sure that you want to perform this action?',
        //     accept: () => {
        //         //Actual logic to perform a confirmation
        //     }
        // });
    }

    onUserNameCheckCompleted(event: boolean): void {
        this.isExistedLoginName = event;

        // if (event) {
        //     this.loginNameClass = { 'has-warning': true, 'has-success': false, 'has-error': false };
        //     this.msgs = [];
        //     this.msgs.push({ severity: 'warn', summary: '提示信息：', detail: '登录名已存在，请重新输入' });
        // } else {
        //     this.loginNameClass = { 'has-warning': false };
        // }
    }

    // checkValueIsRepeated(event: any): void {
    //     this.isExistedLoginName = event.result;
    //     let jqueryElement = $(this.loginNameLocation.nativeElement);

    //     if (event.result) {
    //         jqueryElement.addClass('has-warning');
    //         jqueryElement.removeClass('has-success', 'has-error');
    //         this.msgs = [];
    //         this.msgs.push({ severity: 'warn', summary: '提示信息：', detail: '登录名已存在，请重新输入' });
    //     } else {
    //         jqueryElement.removeClass('has-warning');
    //     }
    // }

    closeGrowl(event: any): void {
        if (event.message.severity === 'success') {
            this.prepareUserData();
            this.router.navigate(['/users']);
        }
    }

    onProvinceSelectedChange(firstAddress: number): void {
        switch (firstAddress) {
            case 1:
                this.secondAddress = this.beijingProvince;
                break;
            case 2:
                this.secondAddress = this.shanghaiProvice;
                break;
        }
    }

    onSubmit(event: NgForm): void {
        if (this.formGroup.controls.birthday.value && typeof (this.formGroup.controls.birthday.value) == 'object') {
            this.formGroup.controls.birthday.setValue(this.formGroup.controls.birthday.value.format('YYYY-MM-DD'));
        }

        if (!this.isExistedLoginName && event.valid) {
            // this.userService.create(this.formGroup.value).subscribe(data => {
            //     if (data.success) {
            //         this.msgs = [];
            //         this.msgs.push({ severity: 'success', summary: '提示信息：', detail: '添加成功' });
            //     } else {
            //         this.msgs = [];
            //         this.msgs.push({ severity: 'error', summary: '提示信息：', detail: '添加失败' });
            //     }
            // });
            // } else {
            //     this.msgs = [];
            //     this.msgs.push({ severity: 'error', summary: '提示信息：', detail: '添加失败，请正确填写' });
        }
    }

    // sendLoginName(newLoginName: string): void {
    //     this.searchName.next(newLoginName);
    // }

    private createForm(): void {
        this.formGroup = this.formBuilder.group({
            name: ['', [
                Validators.required,
                Validators.minLength(2),
                Validators.maxLength(5),
                Validators.pattern(new RegExp(this.legitimateNameOfRegExp)),
            ]],
            loginName: ['', [
                Validators.required,
                Validators.minLength(5),
                Validators.maxLength(16),
                Validators.pattern(new RegExp(this.legitimateAccountOfRegExp)),
            ]],
            password: ['', [
                Validators.required,
                Validators.minLength(6),
                Validators.maxLength(12)
            ]],
            confirmPassword: [''],
            idNumber: ['', [
                Validators.required,
                Validators.pattern(new RegExp(this.legitimateIDCardOfRegExp)),
            ]],
            gender: [''],
            telephone: ['', [
                Validators.required,
                Validators.pattern(new RegExp(this.legitimatePhoneOfRegExp)),
            ]],
            birthday: [''],
            firstAddress: [''],
            secondAddress: [''],
            nationality: [''],
            status: [''],
        });

        this.formGroup.get('confirmPassword').setValidators([
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(12),
            this.validatorFactory.getValueNotMatchValidatorDeprecated(this.formGroup.controls.password, this.formGroup.controls.confirmPassword)
        ]);

        // this.formGroup.controls.loginName.valueChanges.subscribe(() =>
        //     this.sendLoginName(this.formGroup.controls.loginName.value)
        // );

        this.formGroup.controls.password.valueChanges.subscribe(() =>
            this.validatorFactory.setValueNotMatchFieldModelError(this.formGroup.controls.password, this.formGroup.controls.confirmPassword)
        );

        this.formGroup.controls.firstAddress.valueChanges.subscribe(() =>
            this.onProvinceSelectedChange(this.formGroup.controls.firstAddress.value)
        );
    }

    private loadData(): void {
        this.formGroup.setValue({
            name: this.user.name,
            loginName: this.user.loginName,
            password: this.user.password,
            confirmPassword: this.user.confirmPassword,
            idNumber: this.user.idNumber,
            gender: this.user.gender,
            telephone: this.user.telephone,
            birthday: this.user.birthday,
            firstAddress: this.user.firstAddress,
            secondAddress: this.user.secondAddress,
            nationality: this.user.nationality,
            status: this.user.status
        });
    }

    private loadFirstAddress(): void {
        this.userService.getConstant(this.constantOfFirstAddress).subscribe(data => {
            this.firstAddress = data.filter(user => user.constantCode === 400);
        });
    }

    // private loadFirstAddress(): void {
    //     this.userService.getConstant(this.constantOfFirstAddress).subscribe(data => {
    //         this.firstAddress = data.result;
    //     });
    // }

    private loadSecondAddress(): void {
        this.userService.getConstant(this.constantOfSecondAddress).subscribe(data => {
            data.filter(user => user.constantCode === 500).forEach(item => {
                if (item.code <= 3) {
                    this.beijingProvince.push(item);
                } else {
                    this.shanghaiProvice.push(item);
                };
            });
        });
    }

    // private loadSecondAddress(): void {
    //     this.userService.getConstant(this.constantOfSecondAddress).subscribe(data => {
    //         data.result.forEach(item => {
    //             if (item.code <= 3) {
    //                 this.beijingProvince.push(item);
    //             } else {
    //                 this.shanghaiProvice.push(item);
    //             };
    //         });
    //     });
    // }

    private loadNationality(): void {
        this.userService.getConstant(this.constantOfNation).subscribe(data => {
            this.nationality = data.filter(user => user.constantCode === 200);
        });
    }

    // private loadNationality(): void {
    //     this.userService.getConstant(this.constantOfNation).subscribe(data => {
    //         this.nationality = data.result;
    //     });
    // }

    private loadStatus(): void {
        this.userService.getConstant(this.constantOfStatus).subscribe(data => {
            this.status = data.filter(user => user.constantCode === 300);
        });
    }

    // private loadStatus(): void {
    //     this.userService.getConstant(this.constantOfStatus).subscribe(data => {
    //         this.status = data.result;
    //     });
    // }

    private prepareUserData(): void {
        this.user = {
            name: null,
            loginName: null,
            password: null,
            confirmPassword: null,
            idNumber: null,
            gender: null,
            telephone: null,
            birthday: null,
            firstAddress: null,
            secondAddress: null,
            nationality: null,
            status: null
        };
    };
}